const app = getApp()
const request = require('../../../..//utils/request')
const regex = require('../../../../utils/regex')

Page({
  data: {
    placeholderVal: '',
    getCode: true,
    countdownTime: 60,
    btnText: '获取验证码',
    phone: ''
  },

  onLoad() {},

  // 监听手机号码
  bindPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  
  getVerifyCode(event) {
    const { phone } = this.data
    if (!phone) {
      wx.showToast({
        icon: 'none',
        title: '请输入手机号 '
      })
      return
    }

    if (!regex.phone.test(phone)) {
      wx.showToast({
        icon: 'none',
        title: '手机号格式错误'
      })
      return
    }



    wx.showLoading()
    request.get('send_sms', { phone })
      .then(res => {
        wx.hideLoading()
        this.setData({
          getCode: false
        })
    
        let time = event.target.dataset.time
        const t = setInterval(() => {
          time--
          this.setData({
            countdownTime: time
          })
    
          if (time <= 0) {
            clearInterval(t)
            this.setData({
              countdownTime: 60,
              getCode: true,
              btnText: '重新获取'
            })
    
          }
        }, 1000)

        wx.showToast({
          icon: 'none',
          title: res.msg
        })
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg 
        })
      })
      .finally(_ => {
        
      })
  },

  // form 提交
  formSubmit(e) {
    const value = e.detail.value

    if (!value.phone) {
      wx.showToast({
        icon: 'none',
        title: '请输入手机号'
      })
      return
    }

    if (!regex.phone.test(value.phone)) {
      wx.showToast({
        icon: 'none',
        title: '手机号格式错误'
      })
      return
    }

    if (value.yzm === '') {
      wx.showToast({
        icon: 'none',
        title: '请输入验证码'
      })
      return
    }

    if (!value.pwd) {
      wx.showToast({
        icon: 'none',
        title: '请输入密码'
      })
      return
    }

    if (!value.cpwd) {
      wx.showToast({
        icon: 'none',
        title: '请确认密码'
      })
      return
    }

    if (value.pwd !== value.cpwd) {
      wx.showToast({
        icon: 'none',
        title: '两次密码输入不一致'
      })
      return
    }

    const data = {
      phone: value.phone,
      password: value.pwd,
      yzm: value.yzm
    }

    wx.showLoading()
    request.post('forget_password', data)
      .then(res => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: '修改成功'
        })

        setTimeout(() => void wx.switchTab({
          url: '../login'
        }), 1500)

      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg
        })
      })
      .finally(_ => {
        
      })
  },
})